package com.eastcom.collection.script

import java.awt.TexturePaintContext.Int;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress.Cache;
import java.sql.Date;
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eastcom.collection.tools.common.ShellExecutor;
import com.eastcom.collection.tools.db.DbEngine
import com.eastcom.collection.tools.file.FileUtils;
import com.eastcom.collection.tools.file.FtpUtils;
import com.eastcom.groovy.provider.*
import com.eastcom.groovy.tools.mail.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.util.ClassPath.Dir;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
class SimpleTxtFileTaskTool {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String[] ftpRemotePath = [
		"/home/dongxin/lm1",
		"/home/dongxin/lm2",
		"/home/dongxin/portal1",
		"/home/dongxin/portal2",
		"/home/dongxin/portal3",
		"/home/dongxin/portal4",
		"/home/dongxin/portal5",
		"/home/dongxin/portal6",
		"/home/dongxin/portal7",
		"/home/dongxin/radius1",
		"/home/dongxin/radius2",
		"/home/dongxin/radius3",
		"/home/dongxin/radius4",
		"/home/dongxin/radius5",
		"/home/dongxin/radius6",
		"/home/dongxin/mdb1",
		"/home/dongxin/mdb2",
		"/home/dongxin/obs1",
		"/home/dongxin/obs2"]
	final String[] ftpLocalPath = [
		"/home/ipnet/mystope/allconfig/lm1",
		"/home/ipnet/mystope/allconfig/lm2",
		"/home/ipnet/mystope/allconfig/portal1",
		"/home/ipnet/mystope/allconfig/portal2",
		"/home/ipnet/mystope/allconfig/portal3",
		"/home/ipnet/mystope/allconfig/portal4",
		"/home/ipnet/mystope/allconfig/portal5",
		"/home/ipnet/mystope/allconfig/portal6",
		"/home/ipnet/mystope/allconfig/portal7",
		"/home/ipnet/mystope/allconfig/radius1",
		"/home/ipnet/mystope/allconfig/radius2",
		"/home/ipnet/mystope/allconfig/radius3",
		"/home/ipnet/mystope/allconfig/radius4",
		"/home/ipnet/mystope/allconfig/radius5",
		"/home/ipnet/mystope/allconfig/radius6",
		"/home/ipnet/mystope/allconfig/mdb1",
		"/home/ipnet/mystope/allconfig/mdb2",
		"/home/ipnet/mystope/allconfig/obs1",
		"/home/ipnet/mystope/allconfig/obs2"
	]
	final String[][] ftpFileNameRegex =
	[
		["lm.ini\\.(\\d+)"],
		["lm.ini\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["portalserver\\.xml\\.(\\d+)","misc\\.properties\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["radius\\.ini\\.(\\d+)"],
		["configuration\\.xml\\.(\\d+)"],
		["configuration\\.xml\\.(\\d+)"],
		["aiip\\.cfg\\.(\\d+)"],
		["aiip\\.cfg\\.(\\d+)"]
	]
	//没有时间的话用[]
	final String[][] fileNameTimeFormat =
	[
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd","yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"],
		["yyyyMMdd"]
	]
	final String ftpIp = "10.11.244.119"
	final String ftpUser = "dongxin"
	final String ftpPasswd = "dx@wlan"
	final int ftpPort = 21
	final int ftpFileLimit = 200
	final String ftpSystem = "UNIX"
	final String ftpControlEnCode = "UTF-8"
	final String ftpFileEnCode = "UTF-8"
	final String ftpServerLanguage = "zh"
	final long fileLimit = 20000000000
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static Log logger = LogFactory.getLog(SimpleTxtFileTaskTool.class)



	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean doFtp(){
		try{
			FTPFile[] acceptFiles = null;
			FtpUtils ftpUtils = new FtpUtils();
			for(int i = 0; i < ftpRemotePath.length; i++){
				String rp = ftpRemotePath[i]
				String lp = ftpLocalPath[i]
				File dirFile = new File(lp);
				if(! dirFile.exists()){
					dirFile.mkdirs();
				}
				ftpUtils.login(ftpIp, ftpPort, ftpUser, ftpPasswd, ftpSystem, ftpControlEnCode, ftpServerLanguage);
				ftpUtils.getFtp().changeWorkingDirectory(rp);
				String[] fileNameRegex = ftpFileNameRegex[i]
				String[] fileTimeFormat = fileNameTimeFormat[i]
				for(int j = 0; j < fileNameRegex.length; j++){
					String nameRegex = fileNameRegex[j]
					String timeFormat = fileTimeFormat[j]
					Pattern pat = Pattern.compile(nameRegex);
					acceptFiles = ftpUtils.getFtp().listFiles(null, new FTPFileFilter() {
								private int fileCount = 0;
								@Override
								public boolean accept(FTPFile file) {
									// TODO 自动生成的方法存根
									String name = file.getName();
									println name

									Matcher mat = pat.matcher(name);
									boolean rs = mat.find();
									if(! rs){
										return false
									}
									String tm = mat.group(1)
									SimpleDateFormat simp = new SimpleDateFormat(timeFormat)
									java.util.Date date = simp.parse(tm)
									Calendar fileLimitTime = Calendar.getInstance();
									fileLimitTime.setTimeInMillis(new java.util.Date().getTime() - fileLimit);
									if(date.before(fileLimitTime.getTime())){
										return false
									}
									File localFile = new File(lp);
									String[] localFiles = localFile.list();
									if(localFiles != null){
										for(String lf: localFiles){
											if(lf.equalsIgnoreCase(name)){
												return false;
											}
										}
									}

									if(fileCount > ftpFileLimit){
										return false;
									}
									fileCount++;
									return true;
								}
							});
					boolean res = false;
					int count = 0;
					logger.debug("接收的文件数量："+acceptFiles.length);
					for(int k = 0; k < acceptFiles.length; k++){
						String fileName = acceptFiles[k].getName();
						File f = null;
						String dir = lp

						if(dir.endsWith("/")||dir.endsWith("\\")||dir.endsWith("\\\\")){
							f=new File(dir+fileName);
						}else{
							f=new File(dir+"/"+fileName);
						}
						OutputStream os=new FileOutputStream(f);
						res = ftpUtils.getFtp().retrieveFile(new String(fileName.getBytes(ftpFileEnCode),"ISO-8859-1"), os);
						if(res){
							count ++;
						}
						os.flush()
						os.close()
						logger.debug("下载了"+count+"文件！")
					}
				}
			}
		}catch (Exception e) {
			logger.error(this,e)
		}
	}
}